package com.atguigu.tingshu.payment.context;

import com.atguigu.tingshu.payment.strategy.PaymentStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class PaymentStrategyContext implements ApplicationContextAware {
    //定义map存出实现类对象
    private static final Map<String, PaymentStrategy> PAYMENT_STRATEGY_MAP = new HashMap<>();

    //根据支付类型获取支付策略
    public static  PaymentStrategy getpaymentStratege(String paymentType){
        return PAYMENT_STRATEGY_MAP.get(paymentType);
    }
    //在bean运行时给map赋值
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, PaymentStrategy> beansOfType = applicationContext.getBeansOfType(PaymentStrategy.class);
        beansOfType.values().forEach(paymentStrategy -> {
            PAYMENT_STRATEGY_MAP.put(paymentStrategy.getPaymentType(), paymentStrategy);
        });
    }
}
